﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;

namespace IronOne.SalesOne.DataObjects
{
    public class LinqAudit
    {
        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        public List<EventLog> GetEventLogs(int? module, DateTime? from, DateTime? to, string action, string userName, int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                var predicate = PredicateBuilder.True<EventLogEntity>();
                var userpredicate = PredicateBuilder.True<aspnet_User>();

                if (module != null)
                    predicate = predicate.And(p => p.ModuleId == module);

                if (from != null)
                    predicate = predicate.And(p => p.Date >= from);

                if (to != null)
                    predicate = predicate.And(p => p.Date <= to);

                if (action != null)
                    predicate = predicate.And(p => p.Action == action);

                if(userName != null)
                    userpredicate = userpredicate.And(p => p.UserName.Contains(userName));

                var query = from log in db.EventLogEntities.Where(predicate)
                            join user in db.aspnet_Users.Where(userpredicate) on log.DoneBy equals user.UserId
                            join mod in db.ModuleEntities on log.ModuleId equals mod.ModuleId
                            select new EventLog
                            {
                                Action = log.Action,
                                DoneBy = user.UserName,
                                Date = log.Date,
                                Description = log.Description,
                                Module = mod.ModuleName
                            };

                query = query.OrderByDescending(c => c.Date);
                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.ToList();
            }
        }
    }
}
